package flex.cc.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;


/**
 * @author wkangle
 * @className AddressUtil
 * @description 地址相关工具类
 * @time 2022-04-11 09:48:33
 */

public class AddressUtil {

    private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);
    static String AK = "5p7kHpGmdnaSymXefOPOP8GTWn0niWMp"; // 百度地图密钥

    public static void main(String[] args) {
        String dom = "北京市新龙大厦";
        dom = "北京北京市黑泉路12号";
        String coordinate = getCoordinate(dom, "北京市");
        System.out.println("'" + dom + "'的经纬度为：" + coordinate);

        //String coordsFrom1To3 = getGcj02From1To3(coordinate);
        //System.out.println(coordsFrom1To3);

        //String coordsFrom1To5 = getGcj02From1To5(coordinate);
        //System.out.println(coordinate);

        Map<String, Object> addressListByCoordinate = getAddressListByCoordinate(coordinate.split(",")[1] + "," + coordinate.split(",")[0]);
        System.out.println(addressListByCoordinate);
    }

    // 调用百度地图API根据地址，获取坐标
    public static String getCoordinate(String address, String city) {
        if (address != null && !"".equals(address)) {
            address = address.replaceAll("\\s*", "").replace("#", "栋");
            String url = "https://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + AK + "&callback=showLocation$city=" + city;
            System.out.println("url: " + url);
            String json = loadJSON(url);
            if (json != null && !"".equals(json)) {
                JSONObject obj = JSONObject.parseObject(json);
                if ("0".equals(obj.getString("status"))) {
                    double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng"); // 经度
                    double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat"); // 纬度
                    DecimalFormat df = new DecimalFormat("#.######");
                    return df.format(lng) + "," + df.format(lat);
                }
            }
        }
        return null;
    }

    /**
     * @description 将百度地图的坐标bd09ll转为火星坐标（gcj02
     * @param coords 百度坐标
     * @return
     * @author wkangle
     * @time 2022/04/11 0011 13:59
     * @exception/throws
    */
    public static String getCoordsFrom1To3(String coords) {
        String url = "https://api.map.baidu.com/geoconv/v1/?coords=" + coords + "&from=1&to=3&ak=" + AK;
        String json = loadJSON(url);
        if (json != null && !"".equals(json)) {
            JSONObject obj = JSONObject.parseObject(json);
            if ("0".equals(obj.getString("status"))) {
                double lng = JSONObject.parseObject(obj.getJSONArray("result").get(0).toString()).getDouble("x"); // 经度
                double lat = JSONObject.parseObject(obj.getJSONArray("result").get(0).toString()).getDouble("y"); // 纬度
                DecimalFormat df = new DecimalFormat("#.######");
                return df.format(lng) + "," + df.format(lat);
            }
        }
        return null;
    }

    public static String getCoordsFrom1To5(String coords) {
        String url = "https://api.map.baidu.com/geoconv/v1/?coords=" + coords + "&from=1&to=5&ak=" + AK;
        String json = loadJSON(url);
        if (json != null && !"".equals(json)) {
            JSONObject obj = JSONObject.parseObject(json);
            if ("0".equals(obj.getString("status"))) {
                double lng = JSONObject.parseObject(obj.getJSONArray("result").get(0).toString()).getDouble("x"); // 经度
                double lat = JSONObject.parseObject(obj.getJSONArray("result").get(0).toString()).getDouble("y"); // 纬度
                DecimalFormat df = new DecimalFormat("#.######");
                return df.format(lng) + "," + df.format(lat);
            }
        }
        return null;
    }

    /** 根据坐标获取地址详细信息 */
    public static Map<String, Object> getAddressListByCoordinate(String location) {
        Map<String, Object> addressList = new HashMap<>();
        System.out.println("location: " + location);
        String url = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + AK + "&output=json&location=" + location;
        System.out.println(url);
        String json = loadJSON(url);
        if (json != null && !"".equals(json)) {
            JSONObject obj = JSONObject.parseObject(json);
            System.out.println(obj);
            if ("0".equals(obj.getString("status"))) {
                JSONObject result = obj.getJSONObject("result");
                String address = result.get("formatted_address").toString();
                JSONObject addressComponent = JSONObject.parseObject(result.get("addressComponent").toString());
                String province = addressComponent.get("province").toString();
                String city = addressComponent.get("city").toString();
                String district = addressComponent.get("district").toString();
                JSONObject location1 = JSONObject.parseObject(result.get("location").toString());
                Double lng = location1.getDouble("lng");
                Double lat = location1.getDouble("lat");
                addressList.put("address", address);
                addressList.put("province", province);
                addressList.put("city", city);
                addressList.put("district", district);
                addressList.put("lng", lng);
                addressList.put("lat", lat);
            }
        }
        log.info("======= getAddressListByCoordinate addressList =====> {} ", addressList);
        return addressList;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("json ==> {}", json != null ? json.toString() : null);
        return json.toString();
    }

}
